//
//  AppDelegate.swift
//  WeiboPre12
//
//  Created by EnjoySR on 15/12/25.
//  Copyright © 2015年 EnjoySR. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = TFUserAccountViewModel.sharedViewModel.userLogin ? defaultViewController() : TFMainTabBarController()
                
       
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: HMSwitchRootViewControllerNotification, object: nil)
        
         window?.makeKeyAndVisible()
        
        return true
    }
    
    @objc private func switchRootViewController(noti: NSNotification){
        // 切换根控制器
        let vc = noti.object as? UIViewController
        window?.rootViewController = vc is TFOAuthViewController ? TFWelcomeViewController() : TFMainTabBarController()
    }
    
    /// 返回默认要显示的ViewController (登录之后)
    private func defaultViewController() -> UIViewController {
        return isNewVersion() ? TFNewFeatureViewController() : TFWelcomeViewController()
    }
    
    /// 是否是新版本
    ///
    /// - returns: 是否是新版本
    private func isNewVersion() -> Bool {
        
        let versionKey = "sanboxVersionKey"
        // 先从沙盒里面取
        let sanboxVersion = NSUserDefaults.standardUserDefaults().objectForKey(versionKey) as? String
        // 取到本地的version
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        // 将当前版本写入到沙盒
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey)
        
        // 如果已经有沙盒的版本号，并且沙盒的版本号不小于当前的版本号，代表不是新版本
        if let san = sanboxVersion where (san as NSString).compare(currentVersion) != NSComparisonResult.OrderedAscending {
            return false
        }
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: HMSwitchRootViewControllerNotification, object: nil)
    }
}

